import 'dart:convert';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/invite_entity.dart';
import 'package:wanxiang_app/bean/record_list_entity.dart';
import 'package:wanxiang_app/bean/simple_entity.dart';
import 'package:wanxiang_app/utils/common.dart';
import '../../utils/constant.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../utils/user_util.dart';
import '../../widgets/myappbar.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:flutter/services.dart';
import '../home/detail.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'dart:ui' as ui;

class RecordsController extends GetxController{
  EasyRefreshController easyRefreshController = EasyRefreshController(
    controlFinishRefresh: false,
    controlFinishLoad: true,
  );
  GlobalKey globalKey = GlobalKey();

  @override
  void onInit() {
    super.onInit();
    _getService();
    _getUrl();
    _getImageUrl();
  }
  @override
  void onClose() {
    super.onClose();
  }
  List<InviteData> list = [];
  void _getService(){
    DioManager.getInstance().post(ServiceUrl.inviteList,{
      "user_name":UserUtil.getUSER()?.userName.toString()
    }, (data) async {
      InviteEntity bannerEntity = InviteEntity.fromJson(jsonDecode(data));
      list = bannerEntity.data;
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }
  String url = '';
  void _getUrl(){
    DioManager.getInstance().post(ServiceUrl.inviteUrl,{
      "user_name":UserUtil.getUSER()?.userName.toString()
    }, (data) async {
      SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
      url = bannerEntity.msg;
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }
String imgUrl = '';
void _getImageUrl(){
  DioManager.getInstance().post(ServiceUrl.inviteImg,{
    "invitation_code":UserUtil.getUSER()?.invitationCode.toString()
  }, (data) async {
    SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
    imgUrl = bannerEntity.msg+UserUtil.getUSER()!.invitationCode.toString();
  }, (error) {
    ToastUtil.show(error);
  });
}
}




class InvitePage extends   GetView<RecordsController>  {


  late RecordsController controller ;
  late BuildContext context ;
  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<RecordsController>(() => RecordsController());
    controller = Get.find();
    context = context1;

    return GetBuilder<RecordsController>(
      builder: (_){
        return  Scaffold(
            appBar: MyAppBar(context: context, title: '推广邀请',hasLeading: true,),
            backgroundColor: Colors.white,
            body:_content());
      },
    );

  }
  Widget _empty(){
    return Container(
      margin: EdgeInsets.only(top: 80.h),
      alignment: Alignment.center,
      child: Image.asset(Constant.IMG_BASE+'empty.png',width: 150.w,height: 127.h,),
    );
  }

  Widget _content(){
    return Container(
      margin: EdgeInsets.all(10.w),
      child: Column(
        children: [
          _top(),
          Container(
            margin: EdgeInsets.only(top: 10.h),
            alignment: Alignment.centerLeft,
            child: Text('已邀请：(${UserUtil.getUSER()?.invitationNum.toString()})',style: TextStyle(
              color: Color(0xFF333333)
            ),),
          ),
          controller.list.length==0?_empty():_refresh()
        ],
      ),
    );
  }

  Widget _refresh(){
    return Container(
      height: Get.height - 230.h,
      child:  Scaffold(
          body: EasyRefresh(
            header: ClassicHeader(
              dragText: 'Pull to refresh'.tr,
              armedText: 'Release ready'.tr,
              readyText: 'Refreshing...'.tr,
              processingText: 'Refreshing...'.tr,
              processedText: 'Succeeded'.tr,
              noMoreText: 'No more'.tr,
              failedText: 'Failed'.tr,
              messageText: 'Last updated at %T'.tr,
            ),
            footer: ClassicFooter(
              dragText: 'Pull to load'.tr,
              armedText: 'Release ready'.tr,
              readyText: 'Loading...'.tr,
              processingText: 'Loading...'.tr,
              processedText: 'Succeeded'.tr,
              noMoreText: 'No more'.tr,
              failedText: 'Failed'.tr,
              messageText: 'Last updated at %T'.tr,
            ),
            controller: controller.easyRefreshController,
            onRefresh: () async {
            },
            onLoad: () async {
              controller.easyRefreshController.finishLoad(
                  IndicatorResult.noMore );
            },
            child: ListView.separated(
              itemBuilder: (context, index) {
                return _gameItems(controller.list[index]);
              }, separatorBuilder: (BuildContext context, int index) {
              return Container(height: 8.h,color: Color(0xFFF7F8FC),);
            }, itemCount: controller.list.length,
            ),
          )
      )
    );
  }

  Widget _top(){
    return Container(
      padding: EdgeInsets.fromLTRB(5.w,10.w,5.w,10.w),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8.r),
            gradient: const LinearGradient(      //渐变位置
                begin: Alignment.centerLeft, //右上
                end: Alignment.centerRight, //左下
                //渐变颜色[始点颜色, 结束颜色]
                colors: [Color(0xFF7BA7FE), Color(0xFF4BA5FF),Color(0xFF7BAFFE)]
            )

        ),
      child: Column(
        children: [
          Row(
            children: [
              Text('邀请码：${UserUtil.getUSER()?.invitationCode.toString()}',style: TextStyle(
                color: Colors.white,fontSize: 14.sp
              ),),
              IconButton(
                onPressed: () {
                  Clipboard.setData(ClipboardData(text: UserUtil.getUSER()!.invitationCode.toString()));
                  ToastUtil.show('已复制');
                },
                icon: const Icon(
                  Icons.copy,
                  color: Colors.white,
                ),
              )
            ],
          ),
          SizedBox(height: 5.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Container(
                  child: Text('推广链接：'+controller.url+UserUtil.getUSER()!.invitationCode.toString(),style: TextStyle(
                      color: Colors.white,
                      fontSize: 14.sp

                  ),
                    maxLines: 1,
                    textAlign: TextAlign.left,
                    overflow: TextOverflow.ellipsis,
                  ),
                )
              )
              ,
              IconButton(
                onPressed: () {
                  Clipboard.setData(ClipboardData(text: controller.url+UserUtil.getUSER()!.invitationCode.toString()));
                  ToastUtil.show('已复制');
                },
                icon: const Icon(
                  Icons.copy,
                  color: Colors.white,
                ),
              )
            ],
          ),
          InkWell(
            onTap: (){

              print(UserUtil.getUSER()!.invitationCode.toString());
              showDialog(
                  context: context,

                  builder: (context1) {
                    return StatefulBuilder(
                      builder: (context, state) {
                        return Container(
                          child: Material(
                            color: Colors.transparent,
                            child: showDialogContainer(state,context1),
                          ),
                        );
                      },
                    );
                  });
            },
            child:  Container(
              width: 252.w,
              height: 28.h,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15.r),
                color: Color(0xFFBBDDFF),
              ),
              child: Text('生成推广图片',style: TextStyle(
                  fontSize: 12.sp,
                  color: Color(0xffFF007BE5)
              ),),
            )
          )


          
        ],
      ),
    );
  }

  Widget showDialogContainer(Function state,context1) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [

        Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                SizedBox(width: 10.w,),
                IconButton(onPressed: (){
                  Navigator.pop(context1);
                }, icon: Icon(Icons.close,size: 28,color: Colors.white,),)
              ],
            )
            ,
            Image.network(controller.imgUrl, width: 308.w,
              height: 192.h,)
            ,
            InkWell(
                onTap: () async {
                  Common.saveNetworkImage(controller.imgUrl);
                },
                child: Container(
                  margin: EdgeInsets.only(top: 10.h),
                  width: 100.w,
                  height: 40.h,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Color(0xFF007BE5),
                      borderRadius: BorderRadius.circular(20.r)
                  ),
                  child: Text('保存',style: TextStyle(
                      color: Colors.white,
                      fontSize: 18.sp
                  ),),
                )
            )

          ],
        )
      ],
    );
  }
  
  
  Widget showDialogContainer1(Function state,context1) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [

        Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                SizedBox(width: 10.w,),
                IconButton(onPressed: (){
                  Navigator.pop(context1);
                }, icon: Icon(Icons.close,size: 28,color: Colors.white,),)
              ],
            )
          ,
            RepaintBoundary(
                key: controller.globalKey,
              child: Stack(
                children: [
                  Container(
                    width: 308.w,
                    height: 192.h,
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(6.r)
                    ),
                    alignment: Alignment.center,
                    child: Image.asset(Constant.IMG_BASE+'invite.png',width: 292.w,height: 171.h,),
                  ),
                  Positioned(
                    left: 145.w,
                    top: 50.h,
                    child: QrImageView(
                      data: controller.url,
                      version: QrVersions.auto,
                      size: 85.0,
                    ),)
                ],
              )
            )
            ,
            InkWell(
              onTap: () async {
                //检查是否有存储权限
                var status = await Permission.storage.status;
                if (!status.isGranted) {
                  status = await Permission.storage.request();

                  print(status);
                  return;
                }

                RenderRepaintBoundary? boundary = controller.globalKey.currentContext!
                    .findRenderObject() as RenderRepaintBoundary?;
                double dpr = ui.window.devicePixelRatio; // 获取当前设备的像素比
                var image = await boundary!.toImage(pixelRatio: dpr);
                // 将image转化成byte
                ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
                final result = await ImageGallerySaver.saveImage(byteData!.buffer.asUint8List());
                print(result);
                // Navigator.of(context).pop();
              },
              child: Container(
                margin: EdgeInsets.only(top: 10.h),
                width: 100.w,
                height: 40.h,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Color(0xFF007BE5),
                    borderRadius: BorderRadius.circular(20.r)
                ),
                child: Text('保存',style: TextStyle(
                    color: Colors.white,
                    fontSize: 18.sp
                ),),
              )
            )

          ],
        )
      ],
    );
  }

  Widget _gameItems(InviteData item){
    return
      InkWell(
          onTap: (){
          },
          child: Container(
            padding: EdgeInsets.all(10.w),
            margin: EdgeInsets.only(top: 10.h),

            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16),
                color: Colors.white,
              border: Border.all(color:Color(0xfff2f3f5) ,width: 1.w)
            ),
            child:
            Column(
              children: [
                Row(
                  children: [
                    ClipOval(
                        child:  Image.network(Common.realPicPath(item.userPhoto),width: 60.w,height: 60.w,fit: BoxFit.cover,)
                    ),
                    SizedBox(width: 10.w,),
                    Column(
                      children: [
                        Text(item.nickName,
                          style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,),maxLines: 1,    textAlign: TextAlign.left,
                          overflow: TextOverflow.ellipsis,),
                        SizedBox(width: 5.w,),
                        Text(item.userName,
                          style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,),maxLines: 1,    textAlign: TextAlign.left,
                          overflow: TextOverflow.ellipsis,),
                      ],
                    ),
                    SizedBox(width: 10.w,),
                    Text(Common.transferDate(item.regTime),
                      style: TextStyle(color: Color(0xFF999999),fontSize: 14.sp,),maxLines: 1,    textAlign: TextAlign.left,
                      overflow: TextOverflow.ellipsis,),
              
                  ],
                ),
              ],
            )
            ,
          )
      )
    ;
  }

  Widget _second(){
    return Container(
      width: 55.w,
      height: 24.h,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4.r),
          border: Border.all(width: 1.w,color: Color(0xFF4EBCFF))
      ),
      child: Text('可二次',style: TextStyle(
          color: Color(0xFF4EBCFF),
          fontSize: 12.sp
      ),),
    );
  }

  Widget _officer() {
    return Container(
      alignment: Alignment.center,
      width: 53.w,
      height: 20.h,
      child: Image.asset(Constant.IMG_BASE+'baopei.png',width: 52.w,height: 17.h,fit: BoxFit.fitWidth,),
    );
  }

  Widget _info(RecordListData item){
    return Container(
      color: Color(0xFFFBFBFB),
      padding: EdgeInsets.all(10.w),
      child: Column(
        children: [
          Row(
            children: [
              Flexible(
                  flex:1,
                  child:   Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Text('状态:',style: TextStyle(
                              color: Color(0xFF666666),
                              fontSize: 13.sp
                          ),),
                          Text(Common.statusToText(item.status),style: TextStyle(
                              color: Color(0xFFFF9100),
                              fontSize: 13.sp
                          ),)
                        ],
                      ),


                    ],
                  )),
              Flexible(
                flex: 1,
                child:  Text('商品编号：${item.id.toString()}',style: TextStyle(
                    color: Color(0xFF666666),
                    fontSize: 13.sp
                ),),
              ),
            ],
          ),
          SizedBox(height: 7.h,),
          // Row(
          //   children: [
          //     Expanded(
          //       flex: 1,
          //       child:  Text('商品类型:官方',style: TextStyle(
          //           color: Color(0xFF666666),
          //           fontSize: 13.sp
          //       ),),
          //     ),
          //
          //     Expanded(
          //       flex: 1,
          //       child:  Text('营地号:asasasasa',style: TextStyle(
          //           color: Color(0xFF666666),
          //           fontSize: 13.sp
          //       ),),
          //     ),
          //   ],
          // ),
          // SizedBox(height: 7.h,),
          // Row(
          //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
          //   children: [
          //     Text('商品编号：111111111111111111111111',style: TextStyle(
          //         color: Color(0xFF666666),
          //         fontSize: 13.sp
          //     ),),
          //
          //   ],
          // ),
        ],
      ),
    );
  }

  Widget _btn(RecordListData item){
    return InkWell(
        onTap: (){
          Get.to(()=>DetailPage(),arguments: {
            "goods_id":item.id.toString(),
            "record_id":item.channelId.toString(),
            "channel_name":item.channelName,
            "title":item.channelName,
          },preventDuplicates:false);
        },
        child:  Container(
            height: 36.h,
            margin: EdgeInsets.only(top: 26.h,bottom: 20.h),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Color(0xFFF43F50),
              borderRadius: BorderRadius.all(Radius.circular(20.r)),
            ),
            child: Text(
              '查看详情',style: TextStyle(
                fontSize: 13.sp,
                color: Colors.white
            ),
            )
        )
    );
  }
}